Axe
Axe is a logger-agnostic wrapper that normalizes logs regardless of argument style. Great for large development teams, old and new projects, and works with Pino, Bunyan, Winston, console, and more. It is lightweight, performant, highly-configurable, and automatically adds OS, CPU, and Git information to your logs. It supports hooks (useful for masking sensitive data) and dot-notation remapping, omitting, and picking of log metadata properties. Made for Forward Email, Lad, and Cabin.
Table of Contents
Foreword
Axe was built to provide consistency among development teams when it comes to logging. You not only have to worry about your development team using the same approach to writing logs and debugging applications, but you also have to consider that open-source maintainers implement logging differently in their packages.
There is no industry standard as to logging style, and developers mix and match arguments without consistency. For example, one developer may use the approach of console.log('someVariable', someVariable)
and another developer will simply write console.log(someVariable)
. Even if both developers wrote in the style of console.log('someVariable', someVariable)
, there still could be an underlying third-party package that logs differently, or uses an entirely different approach. Furthermore, by default there is no consistency of logs with stdout or using any third-party hosted logging dashboard solution. It will also be almost impossible to spot logging outliers as it would be too time intensive.
No matter how your team or underlying packages style arguments when invoked with logger methods, Axe will clean it up and normalize it for you. This is especially helpful as you can see outliers much more easily in your logging dashboards, and pinpoint where in your application you need to do a better job of logging at. Axe makes your logs consistent and organized.
Axe is highly configurable and has built-in functionality to remap, omit, and pick metadata fields with dot-notation support. Instead of using slow functions like lodash
's omit
, we use a more performant approach.
Axe adheres to the Log4j log levels, which have been established for 21+ years (since 2001). This means that you can use any custom logger (or the default console
), but we strictly support the following log levels:
trace
debug
info
warn
error
fatal
Axe normalizes invocation of logger methods to be called with only two arguments: a String or Error as the first argument and an Object as the second argument. These two arguments are referred to as "message" and "meta" respectively. For example, if you're simply logging a message and some other information:
logger.info('Hello world', { beep: 'boop', foo: true });
Or if you're logging a user, or a variable in general:
logger.info('user', { user: { id: '1' } });
logger.info('someVariable', { someVariable: true });
You might write logs with three arguments (level, message, meta)
using the log
method of Axe's returned logger
instance:
logger.log('info', 'Hello world', { beep: 'boop', foo: true });
Logging errors is just the same as you might do now:
logger.error(new Error('Oops!'));
You might log errors like this:
logger.error(new Error('Oops!'), new Error('Another Error!'));
Or even multiple errors:
logger.error(new Error('Oops!'), new Error('Another Error!'), new Error('Woah!'));
As you can see, Axe combines multiple errors into one – for an easy to read stack trace.
If you simply use logger.log
, then the log level used will be info
, but it will still use the logger's native log
method (as opposed to using info
). If you invoke logger.log
(or any other logging method, e.g. logger.info
, logger.warn
, or logger.error
), then it will consistently invoke the internal logger with these two arguments.
logger.log('hello world');
logger.info('hello world');
logger.warn('uh oh!', { amount_spent: 50 });
As you can see - this is exactly what you'd want your logger output to look like. Axe doesn't change anything out of the ordinary. Now here is where Axe is handy - it will automatically normalize argument style for you:
logger.warn({ hello: 'world' }, 'uh oh');
logger.warn('uh oh', 'foo bar', 'beep boop');
logger.warn('hello', new Error('uh oh!'));
logger.warn(new Error('uh oh!'), 'hello');
Axe has support for format specifiers, and you can even use format specifiers in the browser (uses format-util – has limited number of format specifiers) and Node (uses the built-in util.format method – supports all format specifiers). This feature is built-in thanks to smart detection using format-specifiers.
logger.info('favorite color is %s', 'blue');
As you can see, Axe makes your logs consistent in both Node and browser environments.
Axe's goal is to allow you to log in any style, but make your log output more readable, organized, and clean.
The most impactful feature of Axe is that it makes logger output human-friendly and readable when there are multiple errors.
Normally console
output (and most other loggers) by default will output the following unreadable stack trace:
> console.log(new Error('hello'), new Error('world'));
Error: hello
at REPL6:1:13
at Script.runInThisContext (node:vm:129:12)
at REPLServer.defaultEval (node:repl:566:29)
at bound (node:domain:421:15)
at REPLServer.runBound [as eval] (node:domain:432:12)
at REPLServer.onLine (node:repl:893:10)
at REPLServer.emit (node:events:539:35)
at REPLServer.emit (node:domain:475:12)
at REPLServer.Interface._onLine (node:readline:487:10)
at REPLServer.Interface._line (node:readline:864:8) Error: world
at REPL6:1:33
at Script.runInThisContext (node:vm:129:12)
at REPLServer.defaultEval (node:repl:566:29)
at bound (node:domain:421:15)
at REPLServer.runBound [as eval] (node:domain:432:12)
at REPLServer.onLine (node:repl:893:10)
at REPLServer.emit (node:events:539:35)
at REPLServer.emit (node:domain:475:12)
at REPLServer.Interface._onLine (node:readline:487:10)
at REPLServer.Interface._line (node:readline:864:8)
However with Axe, errors and stack traces are much more readable (we use maybe-combine-errors under the hood):
> logger.log(new Error('hello'), new Error('world'));
Error: hello
at REPL7:1:12
at Script.runInThisContext (node:vm:129:12)
at REPLServer.defaultEval (node:repl:566:29)
at bound (node:domain:421:15)
at REPLServer.runBound [as eval] (node:domain:432:12)
at REPLServer.onLine (node:repl:893:10)
at REPLServer.emit (node:events:539:35)
at REPLServer.emit (node:domain:475:12)
at REPLServer.Interface._onLine (node:readline:487:10)
at REPLServer.Interface._line (node:readline:864:8)
Error: world
at REPL7:1:32
at Script.runInThisContext (node:vm:129:12)
at REPLServer.defaultEval (node:repl:566:29)
at bound (node:domain:421:15)
at REPLServer.runBound [as eval] (node:domain:432:12)
at REPLServer.onLine (node:repl:893:10)
at REPLServer.emit (node:events:539:35)
at REPLServer.emit (node:domain:475:12)
at REPLServer.Interface._onLine (node:readline:487:10)
at REPLServer.Interface._line (node:readline:864:8)
Lastly, Axe works in both server-side and client-side environments (with Node and the browser).
Application Metadata and Information
If you've read the Foreword, you'll know that Axe invokes logger methods with two normalized arguments, message
(String or Error) and meta
(Object).
Axe will automatically add the following metadata and information to the meta
Object argument passed to logger methods:
Property | Type | Description |
---|
meta.level | String | The log level invoked (e.g. "info" ). |
meta.err | Object | Parsed error information using parse-err. |
meta.original_err | Object | If and only if meta.err already existed, this field is preserved as meta.original_err on the metadata object. |
meta.original_meta | Object | If and only if meta already existed as an argument and was not an Object (e.g. an Array), this field is preserved as meta.original_meta on the metadata object. |
meta.app | Object | Application information parsed using parse-app-info. This is not added in Browser environments. See below nested properties. |
meta.app.name | String | Name of the app from package.json . |
meta.app.version | String | Version of the app package.json . |
meta.app.node | String | Version if node.js running the app. |
meta.app.hash | String | The latest Git commit hash; not available when not in a Git repository or if there is no Git commit hash. |
meta.app.tag | String | The latest Git tag; not available when not in a Git repository or if there is no Git tag. |
meta.app.environment | String | The value of process.env.NODE_ENV . |
meta.app.hostname | String | Name of the computer. |
meta.app.pid | Number | Process ID as in process.pid . |
meta.app.cluster | Object | Node cluster information. |
meta.app.os | Object | Node os information. |
meta.app.worker_threads | Object | Node worker_threads information. |
:warning: Note that by default, Axe will not output this additional information for you (since we set the meta.omittedFields
option to [ 'level', 'err', 'app' ]
by default).
Axe will omit from metadata all properties via the default Array from meta.omittedFields
option (see Options below for more insight).
If the argument "meta" is an empty object, then it will not be passed as an argument to logger methods *ndash; because you don't want to see an empty {}
polluting your log metadata. Axe keeps your log output tidy.
If you set meta.omittedFields
to an empty Array, or alternatively use the environment variable AXE_OMIT_META_FIELDS=""
, then application information will be visible:
const Axe = require('axe');
const logger = new Axe({
meta: {
omittedFields: []
}
});
We recommend that you set meta.omittedFields
to an empty Array in production environments for verbosity.
Note that you can also combine meta.omittedFields
with meta.pickedFields
and meta.remappedFields
(in case you want to output specific properties from meta.app
and exclude others – see Options for more insight).
Install
Node
npm:
npm install axe
Browser
See Browser usage below for more information.
Usage
Options
Property | Type | Default Value | Description | |
---|
showStack | Boolean | true | Attempts to parse a boolean value from process.env.AXE_SHOW_STACK ). If this value is true , then if message is an instance of an Error, it will be invoked as the first argument to logger methods. If this is false , then only the err.message will be invoked as the first argument to logger methods. Basically if true it will call logger.method(err) and if false it will call logger.method(err.message) . If you pass err as the first argument to a logger method, then it will show the stack trace via err.stack typically. | |
meta | Object | See below | Stores all meta config information (see the following nested properties below). | |
meta.show | Boolean | true | Attempts to parse a boolean value from process.env.AXE_SHOW_META – meaning you can pass a flag AXE_SHOW_META=true node app.js when needed for debugging), whether or not to output metadata to logger methods. If set to false , then fields will not be omitted nor picked; the entire meta object will be hidden from logger output. | |
meta.remappedFields | Object | {} | Attempts to parse an Object mapping from process.env.AXE_REMAPPED_META_FIELDS (, and : delimited, e.g. REMAPPED_META_FIELDS=foo:bar,beep.boop:beepBoop to remap meta.foo to meta.bar and meta.beep.boop to meta.beepBoop ). Note that this will clean up empty objects by default unless you set the option meta.cleanupRemapping to false ). Supports dot-notation. | |
meta.omittedFields | Array | ['level','err','app'] in Node environments and [] in Browser environments | Attempts to parse an array value from process.env.AXE_OMIT_META_FIELDS (, delimited) - meaning you can pass a flag OMIT_META_FIELDS=user,id node app.js ), determining which fields to omit in the metadata passed to logger methods. Supports dot-notation. | |
meta.pickedFields | Array | [] | Attempts to parse an array value from process.env.AXE_PICK_META_FIELDS (, delimited) - meaning you can pass a flag, e.g. PICK_META_FIELDS=request.headers,response.headers node app.js which would pick from meta.request and meta.response only meta.request.headers and meta.response.headers ), This takes precedence after fields are omitted, which means this acts as a whitelist. Supports dot-notation. | |
meta.cleanupRemapping | Boolean | true | Whether or not to cleanup empty objects after remapping operations are completed) | |
silent | Boolean | false | Whether or not to invoke logger methods. Pre and post hooks will still run even if this option is set to false . | |
logger | Object | console | Defaults to console with console-polyfill added automatically, though you can bring your own logger. See custom logger – you can pass an instance of pino , signale , winston , bunyan , etc. | |
name | String or Boolean | false if NODE_ENV is "development" otherwise the value of process.env.HOSTNAME or os.hostname() | The default name for the logger (defaults to false in development environments, which does not set logger.name ) – this is useful if you are using a logger like pino which prefixes log output with the name set here. | |
level | String | "info" | The default level of logging to invoke logger methods for (defaults to info , which includes all logs including info and higher in severity (e.g. info , warn , error , fatal ) | |
levels | Array | ['info','warn','error','fatal'] | An Array of logging levels to support. You usually shouldn't change this unless you want to prevent logger methods from being invoked or prevent hooks from being run for a certain log level. If an invalid log level is attempted to be invoked, and if it is not in this Array, then no hooks and no logger methods will be invoked. | |
appInfo | Boolean | true | Attempts to parse a boolean value from process.env.AXE_APP_INFO ) - whether or not to parse application information (using parse-app-info). | |
Supported Platforms
-
Node: v14+
-
Browsers (see .browserslistrc):
npx browserslist
and_chr 107
and_ff 106
and_qq 13.1
and_uc 13.4
android 107
chrome 107
chrome 106
chrome 105
edge 107
edge 106
edge 105
firefox 106
firefox 105
firefox 102
ios_saf 16.1
ios_saf 16.0
ios_saf 15.6
ios_saf 15.5
ios_saf 14.5-14.8
kaios 2.5
op_mini all
op_mob 64
opera 91
opera 90
safari 16.1
safari 16.0
safari 15.6
samsung 18.0
samsung 17.0
Node
const Axe = require('axe');
const logger = new Axe();
logger.info('hello world');
Browser
This package requires Promise support, therefore you will need to polyfill if you are using an unsupported browser (namely Opera mini).
We no longer support IE as of Axe v10.0.0+.
VanillaJS
The browser-ready bundle is only 18 KB when minified and 6 KB when gzipped.
<script src="https://polyfill.io/v3/polyfill.min.js?features=Promise"></script>
<script src="https://unpkg.com/axe"></script>
<script type="text/javascript">
(function () {
const logger = new Axe();
logger.info('hello world');
console = new Axe();
console.info('hello world');
});
</script>
Required Browser Features
We recommend using https://polyfill.io (specifically with the bundle mentioned in VanillaJS above):
<script src="https://polyfill.io/v3/polyfill.min.js?features=Promise"></script>
- Promise is not supported in op_mini all
Bundler
If you're using something like browserify, webpack, or rollup, then install the package as you would with Node above.
Custom logger
By default, Axe uses the built-in console
(with console-polyfill for cross-browser support).
However you might want to use something fancier, and as such we support any logger out of the box.
Loggers supported include, but are not limited to:
Just pass your custom logging utility as the logger
option:
const signale = require('signale');
const Axe = require('axe');
const logger = new Axe({ logger: signale });
logger.info('hello world');
In Lad, we have an approach similar to the following, where non-production environments use consola, and production environments use pino.
const Axe = require('axe');
const consola = require('consola');
const pino = require('pino')({
customLevels: {
log: 30
},
hooks: {
logMethod(inputArgs, method) {
return method.call(this, {
msg: inputArgs[0],
meta: inputArgs[1]
});
}
}
});
const isProduction = process.env.NODE_ENV === 'production';
const logger = new Axe({
logger: isProduction ? pino : consola
});
logger.info('hello world');
Silent Logging
Silent logging is useful when you need to disable logging in certain environments for privacy reasons or to simply clean up output on stdout.
For example when you're running tests you can set logger.config.silent = true
.
const Axe = require('axe');
const logger = new Axe({ silent: true });
logger.info('hello world');
Stack Traces and Error Handling
Please see Cabin's documentation for stack traces and error handling for more information.
If you're not using cabin
, you can simply replace instances of the word cabin
with axe
in the documentation examples linked above.
Hooks
You can add synchronous "pre" hooks and/or asynchronous/synchronous "post" hooks with Axe. Both pre and post hooks accept four arguments (level
, err
, message
, and meta
). Pre hooks are required to be synchronous. Pre hooks also run before any metadata is picked, omitted, remapped, etc.
Both pre and post hooks execute serially – and while pre hooks are blocking, post-hooks will run in the background after logger methods are invoked (you can have a post hook that's a Promise or async function).
Pre hooks require an Array to be returned of [ err, message, meta ]
.
Pre hooks allow you to manipulate the arguments err
, message
, and meta
that are passed to the internal logger methods. This is useful for masking sensitive data or doing additional custom logic before writing logs.
Post hooks are useful if you want to send logging information to a third-party, store them into a database, or do any sort of custom processing.
You should properly handle any errors in your pre hooks, otherwise they will be thrown and logger methods will not be invoked.
We will catch errors for post hooks by default and log them as errors with your logger methods' logger.error
method).
Hooks can be defined in the options passed to an instance of Axe, e.g. new Axe({ hooks: { pre: [ fn ], post: [ fn ] } });
and/or with the method logger.pre(level, fn)
or logger.post(level, fn)
. Here are a few examples below:
const Axe = require('axe');
const logger = new Axe({
hooks: {
pre: [
function (level, err, message, meta) {
message = message.replace(/world/gi, 'planet earth');
return [err, message, meta];
}
]
}
});
logger.info('hello world');
const Axe = require('axe');
const logger = new Axe();
logger.pre('error', (err, message, meta) => {
if (err instanceof Error) err.is_beep_boop = true;
return [err, message, meta];
});
logger.error(new Error('oops'));
For more examples of hooks, see our below sections on Send Logs to HTTP Endpoint, Send Logs to Slack), and Suppress Logger Data below.
Remapping
If you would like to remap fields, such as response.headers
to responseHeaders
, then you can use environment variables or pass an object with configuration mapping.
const logger = new Axe({
meta: {
remappedFields: {
'response.headers': 'responseHeaders'
}
}
});
logger.info('foo bar', {
response: {
headers: {
'X-Hello-World': true
}
}
});
Omitting
If you would like to omit fields, such as response.headers
from a response, so you are only left with the status code:
const logger = new Axe({
meta: {
omittedFields: ['level', 'err', 'app', 'response.headers']
}
});
logger.info('foo bar', {
response: {
status: 200,
headers: {
'X-Hello-World': true
}
}
});
Picking
If you would like to pick certain fields, such as response.status
from a response:
const logger = new Axe({
meta: {
pickedFields: [ 'response.status' ]
}
});
logger.info('foo bar', {
response: {
status: 200,
headers: {
'X-Hello-World': true
}
}
});
Aliases
We have provided helper/safety aliases for logger.warn
and logger.error
of logger.warning
and logger.err
respectively.
Methods
A few extra methods are available, which were inspired by Slack's logger and added for compatibility:
logger.setLevel(level)
- sets the log level
(String) severity to invoke logger
methods for (must be valid enumerable level)logger.getNormalizedLevel(level)
- gets the normalized log level
(String) severity (normalizes to known logger levels, e.g. "warning" => "warn", "err" => "error", "log" => "info")logger.setName(name)
- sets the name
(String) property (some loggers like pino
will prefix logs with the name set here)
Examples
Send Logs to HTTP Endpoint
This is an example of using hooks to send a POST request to an HTTP endpoint with logs of the "fatal" and "error" levels that occur in your application:
We recommend superagent, however there are plenty of alternatives such as axios and ky.
-
You will also need to install additional packages:
npm install axe fast-safe-stringify cuid superagent
-
Implementation example is provided below (and you can also refer to the Forward Email code base):
const Axe = require('axe');
const safeStringify = require('fast-safe-stringify');
const cuid = require('cuid');
const superagent = require('superagent');
const logger = new Axe();
async function hook(err, message, meta) {
if (meta.ignore_hook) return;
try {
const request = superagent
.post(`https://api.example.com/v1/log`)
.set(
'X-Request-Id',
meta && meta.request && meta.request.id ? meta.request.id : cuid()
)
.set('X-Axe-Version', logger.config.version)
.timeout(5000);
const response = await request
.type('application/json')
.retry(3)
.send(safeStringify({ err, message, meta }));
logger.info('log sent over HTTP', { response, ignore_hook: true });
} catch (err) {
logger.fatal(err, { ignore_hook: true });
}
}
for (const level of logger.config.levels) {
logger.post(level, hook);
}
Send Logs to Slack
This is an example of using hooks to send a message to Slack with logs of the "fatal" and "error" levels that occur in your application:
-
You will need to install the @slack/web-api
package locally:
npm install @slack/web-api
-
Create and copy to your clipboard a new Slack bot token at https://my.slack.com/services/new/bot.
-
Implementation example is provided below:
Replace INSERT-YOUR-TOKEN
with the token in your clipboard
const os = require('os');
const Axe = require('axe');
const { WebClient } = require('@slack/web-api');
const logger = new Axe({
logger: console,
level: 'info'
});
const web = new WebClient('INSERT-YOUR-TOKEN', {
logger,
logLevel: logger.config.level
});
async function hook(err, message, meta) {
if (meta.ignore_hook) return;
try {
const result = await web.chat.postMessage({
channel: 'monitoring',
username: 'Axe',
icon_emoji: ':axe:',
attachments: [
{
title: err && err.message ? err.message : message,
color: 'danger',
text: err && err.stack ? err.stack : message,
fields: [
{
title: 'Level',
value: meta.level,
short: true
},
{
title: 'Environment',
value: meta.app.environment,
short: true
},
{
title: 'Hostname',
value: meta.app.hostname,
short: true
},
{
title: 'Hash',
value: meta.app.hash,
short: true
}
]
}
]
});
logger.info('slack message sent', { result });
} catch (err) {
logger.fatal(err, { ignore_hook: true });
}
}
logger.post('error', hook);
logger.post('fatal', hook);
logger.error(new Error('Uh oh something went wrong!'));
Send Logs to Sentry
See below example and the reference at https://docs.sentry.io/platforms/node/ for more information.
npm install @sentry/node
const Axe = require('axe');
const Sentry = require('@sentry/node');
const logger = new Axe();
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
});
for (const level of logger.config.levels) {
logger.post(level, (err, message, meta) => {
if (err) {
Sentry.captureException(err, meta);
} else {
Sentry.captureMessage(message, meta);
}
});
}
logger.error(new Error('uh oh'));
Suppress Logger Data
This is an example of using a custom hook to manipulate logger arguments to suppress sensitive data.
const Axe = require('.');
const logger = new Axe();
for (const level of logger.config.levels) {
const fn = logger.config.logger[level];
logger.config.logger[level] = function (message, meta) {
if (typeof message === 'string') message = message.replace(/beep/g, 'boop');
if (meta?.data?.beep)
meta.data.beep = Array.from({ length: meta.data.beep.length })
.fill('*')
.join('');
return Reflect.apply(fn, this, [message, meta]);
};
}
logger.warn('hello world beep');
logger.info('start', {
data: {
foo: 'bar',
beep: 'boop'
}
});
logger.error(new Error('oops!'), {
data: {
beep: 'beep-boop-beep'
}
});
Contributors
License
MIT © Nick Baugh